package cn.springcloud.fix.auth.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static final String RESOURCE_ID = "rid";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 如果关闭 stateless，则 accessToken 使用时的 session id 会被记录，后续请求不携带 accessToken 也可以正常响应
        resources.resourceId(RESOURCE_ID).stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)//让 Spring Security 不创建和使用 session
                .and()
                .anonymous()
                .and()
                .authorizeRequests()
                .antMatchers("/auth/product/**").access("#oauth2.hasScope('app') and hasPermission('select') or hasAnyRole('ROLE_USER')")
                .antMatchers("/auth/order/**").authenticated();//配置order访问控制，必须认证过后才可以访问
    }
}
